package com.work.saturn.assets;

/**
 * @author Administrator
 * @content 支付Fragment
 * @date 2018/8/10
 */

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.immo.libcommon.base.BaseBean;
import com.immo.libcommon.constant.BaseUrl;
import com.immo.libcommon.constant.RouterUtil;
import com.immo.libcommon.http.NetworkRequest;
import com.immo.libcommon.utils.MD5Util;
import com.immo.libcommon.utils.ToastUtils;
import com.work.saturn.R;
import com.work.saturn.bean.InterestSubmitBean;
import com.work.saturn.bean.MessageEvent;
import com.work.saturn.bean.TurnOutBean;
import com.work.saturn.main.MainActivity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

/**
 * 底部弹窗Fragment
 */
@SuppressLint("ValidFragment")
public class PayDetailFragment extends DialogFragment {
    private RelativeLayout rePayWay, rePayDetail, reBalance;
    private LinearLayout LinPayWay;
    private RelativeLayout linPass;
    private ListView lv;
    private Button btnPay;
    private EditText gridPasswordView;
    private String target;
    private String amount;
    private String userId;
    private String name;
    private TextView addr;
    private TextView wallet;
    private TextView pay_num;
    private Button paySubmit;
    private String gas;
    private TextView GASText;
    private int type;
    private String chooseOption;
    private String FutureName;
    private TextView re_pay_type;
    private String bz;


    private ImageView imageCloseOne,imageCloseTwo,imageCloseThree;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    @SuppressLint("ValidFragment")
    public PayDetailFragment(String tokenName, String target, String amount, String userId,String Gas,int type,String bz){
      this.name=tokenName;
      this.target=target;
      this.amount=amount;
      this.userId=userId;
      this.gas=Gas;
      this.type=type;
      this.bz=bz;
    }
    @SuppressLint("ValidFragment")
    public PayDetailFragment(String tokenName, String target, String amount, String userId,String Gas,int type,String future,String chooseop){
        this.name=tokenName;
        this.target=target;
        this.amount=amount;
        this.userId=userId;
        this.gas=Gas;
        this.type=type;
        this.FutureName=future;
        this.chooseOption=chooseop;
    }
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // 使用不带Theme的构造器, 获得的dialog边框距离屏幕仍有几毫米的缝隙。
        Dialog dialog = new Dialog(getActivity(), R.style.BottomDialog);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定
        dialog.setContentView(R.layout.fragment_pay_detail);
        dialog.setCanceledOnTouchOutside(true); // 外部点击取消
        // 设置宽度为屏宽, 靠近屏幕底部。
        final Window window = dialog.getWindow();
        window.setWindowAnimations(R.style.AnimBottom);
        final WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.BOTTOM; // 紧贴底部
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平
        lp.height = getActivity().getWindowManager().getDefaultDisplay().getHeight() * 3 / 5;
        window.setAttributes(lp);

        initView(dialog);


        if (getDialog() != null) {
            getDialog().setOnKeyListener((anInterface, keyCode, event) -> {
                if(keyCode==KeyEvent.KEYCODE_ENTER&&event.getAction()==KeyEvent.ACTION_DOWN){
                    if(!TextUtils.isEmpty(gridPasswordView.getText().toString().trim())){
                        if("123456".equals(gridPasswordView.getText().toString().trim())){
                            //TODO 跳转支付宝支付
                        }
                    }
                }else{
                    Toast.makeText(getContext(),"密码不能为空",Toast.LENGTH_SHORT).show();
                }
                return false;
            });
        }



        return dialog;
    }

    private void initView(Dialog dialog) {
        re_pay_type=dialog.findViewById(R.id.re_pay_type);
        if (type==1){
            re_pay_type.setText("转账");
        }else {
            re_pay_type.setText("下注");
        }
        rePayWay =  dialog.findViewById(R.id.re_pay_way);
        rePayDetail = dialog.findViewById(R.id.re_pay_detail);//付款详情
        LinPayWay = dialog.findViewById(R.id.lin_pay_way);//付款方式
        lv = dialog.findViewById(R.id.lv_bank);//付款方式（银行卡列表）
        reBalance = dialog.findViewById(R.id.re_balance);//付款方式（余额）
        btnPay = dialog.findViewById(R.id.btn_confirm_pay);
        gridPasswordView = dialog.findViewById(R.id.pass_view);
        linPass = dialog.findViewById(R.id.lin_pass);
        imageCloseOne= dialog.findViewById(R.id.close_one);
        imageCloseTwo= dialog.findViewById(R.id.close_two);
        imageCloseThree=  dialog.findViewById(R.id.close_three);
        btnPay.setOnClickListener(listener);
        imageCloseOne.setOnClickListener(listener);
        imageCloseTwo.setOnClickListener(listener);
        imageCloseThree.setOnClickListener(listener);
        addr=dialog.findViewById(R.id.re_pay_addr);
        addr.setText(target);
        wallet=dialog.findViewById(R.id.re_pay_walle);
        wallet.setText(userId);
        pay_num=dialog.findViewById(R.id.pay_num);
        pay_num.setText(amount+name);
        paySubmit=dialog.findViewById(R.id.btn_confirm_pay02);
        paySubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (type==1){
                    TurnOutNet(); 
                }else {
                    interestSubmitNet();
                }
            }
        });
        GASText=dialog.findViewById(R.id.re_pay_gas);
        GASText.setText(gas +name);


    }

    /**
     * 未来局下注接口请求
     */
    private void interestSubmitNet() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("futureBureauName", FutureName);
        params.put("chooseOption", chooseOption);
        params.put("password", MD5Util.md5Password(gridPasswordView.getText().toString()));
        params.put("amount", Float.valueOf(amount));

        new NetworkRequest((object, data) -> {
            if (object instanceof BaseBean) {
                BaseBean interestSubmitBean = (BaseBean) object;
                if (interestSubmitBean.isSuccess()) {
                    EventBus.getDefault().post(new MessageEvent("更新首页数据"));
                    Toast.makeText(getActivity(),"下注成功",Toast.LENGTH_SHORT).show();
                    getDialog().dismiss();
                    ARouter.getInstance().build(RouterUtil.MAIN_PAGE).withFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK)
                            .navigation();
                } else {
                    Toast.makeText(getActivity(),interestSubmitBean.getMessage(),Toast.LENGTH_SHORT).show();
                }
            }
        }).requestPost(BaseUrl.INTERESTSUBMIT, getActivity(), JSON.toJSONString(params), InterestSubmitBean.class, true, false);
    }

    /**
     * 转出
     */
    private void TurnOutNet() {
        if (gridPasswordView.getText().toString().length()==0){
            ToastUtils.showToast(getActivity(),"请输入密码");
            return;
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("token", name);
        params.put("target", target);
        params.put("amount", Float.valueOf(amount));
        params.put("password", MD5Util.md5Password(gridPasswordView.getText().toString()));
        params.put("metadata",bz);
        new NetworkRequest((object, data) -> {
            if (object instanceof TurnOutBean) {
                TurnOutBean turnOutBean = (TurnOutBean) object;
                if (turnOutBean.isSuccess()) {
                    Toast.makeText(getActivity(),"转出成功",Toast.LENGTH_SHORT).show();
                    getDialog().dismiss();
                    ARouter.getInstance().build(RouterUtil.MAIN_PAGE).withFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK)
                            .navigation();
                } else {
                    Toast.makeText(getActivity(),turnOutBean.getMessage(),Toast.LENGTH_SHORT).show();
                }
            }
        }).requestPost(BaseUrl.TURNOUT,
                getActivity(), JSON.toJSONString(params), TurnOutBean.class, true, false);
    }

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Animation slide_left_to_left = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_left_to_left);
            Animation slide_right_to_left = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_right_to_left);
            Animation slide_left_to_right = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_left_to_right);
            Animation slide_left_to_left_in = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_left_to_left_in);
            switch (view.getId()) {
                case R.id.re_pay_way://选择方式
                    rePayDetail.startAnimation(slide_left_to_left);
                    rePayDetail.setVisibility(View.GONE);
                    LinPayWay.startAnimation(slide_right_to_left);
                    LinPayWay.setVisibility(View.VISIBLE);
                    break;
                case R.id.re_balance:
                    rePayDetail.startAnimation(slide_left_to_left_in);
                    rePayDetail.setVisibility(View.VISIBLE);
                    LinPayWay.startAnimation(slide_left_to_right);
                    LinPayWay.setVisibility(View.GONE);
                    break;
                case R.id.btn_confirm_pay://确认付款
                    rePayDetail.startAnimation(slide_left_to_left);
                    rePayDetail.setVisibility(View.GONE);
                    linPass.startAnimation(slide_right_to_left);
                    linPass.setVisibility(View.VISIBLE);
                    break;
                case R.id.close_one:
                    getDialog().dismiss();
                    break;
                case R.id.close_two:
                    getDialog().dismiss();
                    break;
                case R.id.close_three:
                    getDialog().dismiss();
                    break;
                default:
                    break;
            }
        }
    };
}
